var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

exports.findByWorkLocationAndTerminal = function(workLocationId, terminalId, completeFun){
    var entity = entityCollection.getEntity("StationUser");
    entity.find(
        { WorkLocation: workLocationId, Terminal: terminalId }, 
        {},
        { path: 'User' }, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询作业工位交叉表错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

//按条件查询上岗记录
exports.findByCondition = function (condition,completeFun) {
    var entity = entityCollection.getEntity("StationUser");
    entity.findOne(condition, null, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });

};

// 新增一条用户上岗记录
exports.insert = function (stationUserRecord) {
    var deferred = Q.defer();

    var stationUserEntity = entityCollection.getEntity("StationUser");
    stationUserEntity.insert(stationUserRecord, function (err, newRecord) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '新增上岗记录错误';
            newErr.message = '新增上岗记录失败';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(newRecord);
    });

    return deferred.promise;
};

// 根据工位查找最近一条用户上岗记录
exports.findLastAttendance = function (workLocationId, projection, populate) {
    var deferred = Q.defer();

    projection = projection ? projection : {};

    var entity = entityCollection.getEntity("StationUser");
    var cursor = entity.Entity
    .find({ WorkLocation: workLocationId}, projection)
    .sort({ StartDateTime: -1 })
    .limit(1);
    
    if (populate) {
        cursor = cursor.populate(populate);
    }
    cursor.exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询用户上岗记录错误';
            newErr.message = '查询用户上岗记录失败';
            deferred.reject(newErr);
            return;
        }
        if (records.length > 0) {
            deferred.resolve(records[0]);
            return;
        } 
        deferred.resolve(null);
    });

    return deferred.promise;
};

// 查找工位当天该时间段所有上岗记录
exports.findDurationAttendance = function (workLocationId, startTime, endTime, projection) {
    var deferred = Q.defer();

    var nowDate = new Date(),
        realStartTime = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 
            startTime.getHours(), startTime.getMinutes(), startTime.getSeconds()),
        realEndTime = new Date(realStartTime);
    realEndTime.setMilliseconds(realEndTime.getMilliseconds() + (endTime - startTime));

    if (!projection) {
        projection = {};
    }
    var entity = entityCollection.getEntity("StationUser");

    entity.Entity
    .find({
        WorkLocation: workLocationId,
        StartDateTime: { $gte: realStartTime, $lte: realEndTime }
    }, projection)
    .distinct('User')
    .then(function (records) {
        deferred.resolve(records);
    }, function () {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询上岗记录错误';
        newErr.message = '查询上岗记录失败，请检查查询参数！';
        deferred.reject(newErr);
    });

    return deferred.promise;
};